﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace Infrastructure
{
    /// <summary>
    /// Http网络访问服务类
    /// </summary>
    public class HttpHelper
    {
        private string _NetWorkSignKey = "";

        /// <summary>
        /// 检验签名key
        /// </summary>
        public string NetWorkSignKey
        {
            get { return _NetWorkSignKey; }
            set { _NetWorkSignKey = value; }
        }

        private bool _UseSign = false;

        /// <summary>
        /// 是否需要签名
        /// </summary>
        public bool UseSign
        {
            get { return _UseSign; }
            set { _UseSign = value; }
        }

        private int _TimeOut = 600 * 1000;

        /// <summary>
        /// 超时时间(默认10分钟)
        /// </summary>
        public int TimeOut
        {
            get { return _TimeOut; }
            set { _TimeOut = value; }
        }

        /// <summary>
        /// http Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="strPost"></param>
        /// <param name="HeaderParam"></param>
        /// <returns></returns>
        public ResponseData HttpPost(string url, string strPost, Dictionary<string, string> HeaderParam, Encoding encoding)
        {
            //string strPost = MakePostUrl(PostData);
            return HttpRequestProc(url, strPost, HeaderParam, encoding);
        }

        /// <summary>
        /// Http Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="HeaderParam"></param>
        /// <returns></returns>
        public ResponseData HttpGet(string url, Dictionary<string, string> HeaderParam, Encoding encoding)
        {
            return HttpRequestGet(url, HeaderParam, encoding);
        }

        /// <summary>
        /// 建造url
        /// </summary>
        /// <param name="PostData"></param>
        /// <returns></returns>
        private string MakePostUrl(Dictionary<string, string> PostData)
        {
            string url = "";

            foreach (KeyValuePair<string, string> KVP in PostData)
            {
                url = url + KVP.Key.Trim() + "=" + KVP.Value.Trim() + "&";
            }
            if (url.Trim() != "")
            {
                url = url.Remove(url.Length - 1, 1);

                if (_UseSign && _NetWorkSignKey.Trim() != "")
                {
                    string Newurl = url + "&key=" + NetWorkSignKey.Trim();
                    url = url + "sign=" + MakeSign(Newurl);
                }
            }
            return url;
        }

        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="inputString"></param>
        /// <returns></returns>
        private string MakeSign(string inputString)
        {
            byte[] result = Encoding.UTF8.GetBytes(inputString);    //为输入密码的文本框
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "");  //为输出加密文本
        }

        private ResponseData HttpRequestGet(string url, Dictionary<string, string> HeaderParam, Encoding encoding)
        {
            ResponseData result = new ResponseData();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = _TimeOut;
            request.Method = "GET";
            //request.Connection = "keep-alive";
            if (HeaderParam != null)
            {
                foreach (KeyValuePair<string, string> d in HeaderParam)
                {
                    request.Headers.Add(d.Key, d.Value);
                }
            }

            request.ContentType = "application/x-www-form-urlencoded";


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (Stream responseSteam = response.GetResponseStream())
            {
                long ContentLength = response.ContentLength;
                if (ContentLength == -1 || ContentLength > 65536)
                {
                    ContentLength = 65536;
                }

                List<byte> ByteList = new List<byte>();
                while (true)
                {
                    byte[] ConstBuffer = new byte[ContentLength];
                    int ireadCount = responseSteam.Read(ConstBuffer, 0, ConstBuffer.Length);

                    if (ireadCount <= 0) break;


                    byte[] NewByte = new byte[ireadCount];

                    Array.Copy(ConstBuffer, 0, NewByte, 0, ireadCount);

                    foreach (byte b in NewByte)
                    {
                        ByteList.Add(b);
                    }
                }


                for (int i = 0; i < response.Headers.Count; i++)
                {
                    string value = response.Headers[i];
                    string key = response.Headers.Keys[i];
                    result.HeaderResponse.Add(key, value);
                }
                result.Data = ByteList.ToArray();

                result.ResponseValue = encoding.GetString(ByteList.ToArray());
            }

            return result;
        }

        private ResponseData HttpRequestProc(string url, string postUrl, Dictionary<string, string> HeaderParam, Encoding encoding)
        {
            ResponseData result = new ResponseData();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = _TimeOut;
            request.Method = "POST";
            //request.Connection = "keep-alive";
            if (HeaderParam != null)
            {
                foreach (KeyValuePair<string, string> d in HeaderParam)
                {
                    request.Headers.Add(d.Key, d.Value);
                }
            }

            using (Stream requestSteam = request.GetRequestStream())
            {
                byte[] b = Encoding.UTF8.GetBytes(postUrl);

                requestSteam.Write(b, 0, b.Length);
            }

            request.ContentType = "application/x-www-form-urlencoded";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (Stream responseSteam = response.GetResponseStream())
            {
                long ContentLength = response.ContentLength;
                if (ContentLength == -1 || ContentLength > 65536)
                {
                    ContentLength = 65536;
                }

                List<byte> ByteList = new List<byte>();
                while (true)
                {
                    byte[] ConstBuffer = new byte[ContentLength];
                    int ireadCount = responseSteam.Read(ConstBuffer, 0, ConstBuffer.Length);

                    if (ireadCount <= 0) break;


                    byte[] NewByte = new byte[ireadCount];

                    Array.Copy(ConstBuffer, 0, NewByte, 0, ireadCount);

                    foreach (byte b in NewByte)
                    {
                        ByteList.Add(b);
                    }
                }

                for (int i = 0; i < response.Headers.Count; i++)
                {
                    string value = response.Headers[i];
                    string key = response.Headers.Keys[i];
                    result.HeaderResponse.Add(key, value);
                }
                result.Data = ByteList.ToArray();

                result.ResponseValue = encoding.GetString(ByteList.ToArray());
            }

            return result;
        }

        /// <summary>
        /// http Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="PostData"></param>
        /// <param name="HeaderParam"></param>
        /// <returns></returns>
        public string HttpPost(string url, Dictionary<string, string> PostData, Dictionary<string, string> HeaderParam)
        {
            string strPost = MakePostUrl(PostData);
            return HttpRequestProc(url, strPost, HeaderParam);
        }

        private string HttpRequestProc(string url, string postUrl, Dictionary<string, string> HeaderParam)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = _TimeOut;
            request.Method = "POST";
            //request.Connection = "keep-alive";
            if (HeaderParam != null)
            {
                foreach (KeyValuePair<string, string> d in HeaderParam)
                {
                    request.Headers.Add(d.Key, d.Value);
                }
            }

            using (Stream requestSteam = request.GetRequestStream())
            {
                byte[] b = Encoding.UTF8.GetBytes(postUrl);

                requestSteam.Write(b, 0, b.Length);
            }

            request.ContentType = "application/x-www-form-urlencoded";


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (Stream responseSteam = response.GetResponseStream())
            {
                long ContentLength = response.ContentLength;
                if (ContentLength == -1 || ContentLength > 65536)
                {
                    ContentLength = 65536;
                }

                List<byte> ByteList = new List<byte>();
                while (true)
                {
                    byte[] ConstBuffer = new byte[ContentLength];
                    int ireadCount = responseSteam.Read(ConstBuffer, 0, ConstBuffer.Length);

                    if (ireadCount <= 0) break;


                    byte[] NewByte = new byte[ireadCount];

                    Array.Copy(ConstBuffer, 0, NewByte, 0, ireadCount);

                    foreach (byte b in NewByte)
                    {
                        ByteList.Add(b);
                    }
                }

                return Encoding.UTF8.GetString(ByteList.ToArray());
            }
        }
    }

    public class ResponseData
    {
        private Dictionary<string, string> _HeaderResponse = new Dictionary<string, string>();

        public Dictionary<string, string> HeaderResponse
        {
            get { return _HeaderResponse; }
            set { _HeaderResponse = value; }
        }

        private string _ResponseValue = "";

        public string ResponseValue
        {
            get { return _ResponseValue; }
            set { _ResponseValue = value; }
        }

        private byte[] _Data = new byte[0];

        public byte[] Data
        {
            get { return _Data; }
            set { _Data = value; }
        }
    }
}
